<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>学分统计</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          icon="el-icon-refresh"
          @click="refreshStats"
        >刷新</el-button>
      </div>

      <!-- 用户选择 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="用户">
          <el-select v-model="queryParams.userId" placeholder="请选择用户" @change="handleUserChange">
            <el-option
              v-for="user in userOptions"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getStats">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="card-row">
        <el-col :span="8">
          <el-card shadow="hover" class="stat-card">
            <div slot="header" class="clearfix">
              <span>总学分</span>
            </div>
            <div class="card-content">
              <div class="card-value">{{ statsData.totalCredit || 0 }}</div>
              <div class="card-label">学分</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="stat-card">
            <div slot="header" class="clearfix">
              <span>活动参与数</span>
            </div>
            <div class="card-content">
              <div class="card-value">{{ statsData.recordCount || 0 }}</div>
              <div class="card-label">活动</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="stat-card">
            <div slot="header" class="clearfix">
              <span>当前学期学分</span>
            </div>
            <div class="card-content">
              <div class="card-value">{{ currentSemesterCredit || 0 }}</div>
              <div class="card-label">学分</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>学期学分分布</span>
            </div>
            <div class="chart-container">
              <div ref="semesterChart" style="width: 100%; height: 300px;"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>学分趋势</span>
            </div>
            <div class="chart-container">
              <div ref="trendChart" style="width: 100%; height: 300px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 学分记录表格 -->
      <el-card shadow="hover" class="table-card">
        <div slot="header" class="clearfix">
          <span>学分记录明细</span>
        </div>
        <el-table
          v-loading="loading"
          :data="creditRecords"
          style="width: 100%"
          border
        >
          <el-table-column label="活动名称" align="center" prop="activityName" :show-overflow-tooltip="true" />
          <el-table-column label="学分值" align="center" prop="creditValue" />
          <el-table-column label="学期" align="center" prop="semester" />
          <el-table-column label="获得时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="statusOptions" :value="scope.row.status" />
            </template>
          </el-table-column>
        </el-table>
        
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getRecords"
        />
      </el-card>
    </el-card>
  </div>
</template>

<script>
import { getUserCreditStats } from "@/api/secondclass/credit";
import { listCredit } from "@/api/secondclass/credit";
import { listUser } from "@/api/system/user";
import { getCurrentSemester } from "@/api/secondclass/credit";
import * as echarts from 'echarts';
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "CreditStats",
  dicts: ['credit_status'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 学分记录表格数据
      creditRecords: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        status: "1" // 默认只查询已通过的学分
      },
      // 用户选项
      userOptions: [],
      // 统计数据
      statsData: {
        totalCredit: 0,
        recordCount: 0,
        semesterCredits: {}
      },
      // 当前学期
      currentSemester: "",
      // 图表实例
      semesterChart: null,
      trendChart: null
    };
  },
  computed: {
    statusOptions() {
      return this.dict.type.credit_status;
    },
    currentSemesterCredit() {
      if (this.statsData.semesterCredits && this.currentSemester) {
        return this.statsData.semesterCredits[this.currentSemester] || 0;
      }
      return 0;
    }
  },
  created() {
    this.getUsers();
    this.getCurrentSemester();
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    if (this.semesterChart) {
      this.semesterChart.dispose();
    }
    if (this.trendChart) {
      this.trendChart.dispose();
    }
  },
  methods: {
    parseTime,
    /** 查询用户列表 */
    getUsers() {
      listUser().then(response => {
        this.userOptions = response.rows;
        if (this.userOptions.length > 0) {
          this.queryParams.userId = this.userOptions[0].userId;
          this.getStats();
        }
      });
    },
    /** 获取当前学期 */
    getCurrentSemester() {
      getCurrentSemester().then(response => {
        this.currentSemester = response.data;
      });
    },
    /** 获取学分统计 */
    getStats() {
      if (!this.queryParams.userId) {
        this.$message.warning("请选择用户");
        return;
      }
      this.loading = true;
      getUserCreditStats(this.queryParams.userId).then(response => {
        this.statsData = response.data;
        this.updateCharts();
        this.getRecords();
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 获取学分记录 */
    getRecords() {
      this.loading = true;
      listCredit({
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        userId: this.queryParams.userId,
        status: this.queryParams.status
      }).then(response => {
        this.creditRecords = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 用户选择变更 */
    handleUserChange(userId) {
      this.queryParams.userId = userId;
      this.getStats();
    },
    /** 刷新统计 */
    refreshStats() {
      this.getStats();
    },
    /** 初始化图表 */
    initCharts() {
      // 初始化学期学分分布图表
      this.semesterChart = echarts.init(this.$refs.semesterChart);
      
      // 初始化学分趋势图表
      this.trendChart = echarts.init(this.$refs.trendChart);
      
      // 设置初始配置
      this.updateCharts();
    },
    /** 更新图表数据 */
    updateCharts() {
      if (!this.semesterChart || !this.trendChart) {
        return;
      }
      
      // 更新学期学分分布图表
      const semesterData = this.statsData.semesterCredits || {};
      const semesters = Object.keys(semesterData).sort();
      const semesterValues = semesters.map(semester => semesterData[semester]);
      
      this.semesterChart.setOption({
        title: {
          text: '学期学分分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: semesters
        },
        series: [
          {
            name: '学分分布',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: semesters.map((semester, index) => ({
              name: semester,
              value: semesterValues[index]
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });
      
      // 更新学分趋势图表
      this.trendChart.setOption({
        title: {
          text: '学分趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: semesters
        },
        yAxis: {
          type: 'value',
          name: '学分'
        },
        series: [
          {
            name: '学期学分',
            type: 'bar',
            data: semesterValues,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '累计学分',
            type: 'line',
            data: this.calculateCumulativeCredits(semesters, semesterValues),
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      });
    },
    /** 计算累计学分 */
    calculateCumulativeCredits(semesters, values) {
      const result = [];
      let sum = 0;
      
      for (let i = 0; i < values.length; i++) {
        sum += parseFloat(values[i]);
        result.push(sum.toFixed(2));
      }
      
      return result;
    },
    /** 调整图表大小 */
    resizeCharts() {
      if (this.semesterChart) {
        this.semesterChart.resize();
      }
      if (this.trendChart) {
        this.trendChart.resize();
      }
    }
  }
};
</script>

<style scoped>
.card-row {
  margin-bottom: 20px;
}
.chart-row {
  margin-bottom: 20px;
}
.table-card {
  margin-top: 20px;
}
.stat-card {
  height: 120px;
}
.card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
.card-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}
.chart-container {
  width: 100%;
  height: 300px;
}
</style> 